$(function() {
	// jQuery选择器上下文
	var	$pg = DWZ.context(), $graph_panel = $('#graph_panel', $pg), 
		$graph = $('#graph', $graph_panel), $img = $('#processAttachmentGraph', $graph), $hotMap = $('#defectGraphHotMap', $graph),
		$filter_panel = $('#filter_panel', $graph_panel),
		$tab_panel = $('#defectGraphSearchTab', $pg),
		$grid_panel = $('#productionControlsGrid', $pg);
	
	// 局部方法
	// 根据条件查找订单明细列表，回调函数填充数据列表
	var selectProductionDetails = function(data) {
		initGrapth();
		$('#productionDetailsGrid', $tab_panel).jGrid('loadData', data);
		$('.tabsHeaderContent li:eq(1)', $tab_panel).click();
		if ($grid_panel.find('td.noData').length == 0) {
			$grid_panel.jGrid('fillGrid', []);
		}
	}, 
	// 根据订单明细中的工作中心、订单号，工艺编号，公益版本查询相应的质检工序以及该订单在个工序上的缺陷数列表
	selectProcessOperations = function(data) {
		initGrapth();
		$('#defectCheck', $grid_panel).attr('checked', false);
		$grid_panel.jGrid('loadData', {
			siteCode : data.siteCode,
			workCenterCode : data.workCenterCode,
			processCode : data.processCode,
			processRev : data.processRev,
			productionOrderNum : data.productionOrderNum,
			productionControlNum:data.productionControlNum
		});
	}, 
	// 根据订单编号，质检工艺图查询，该订单的缺陷记录列表
	selectInspectRecords = function(data) {
		initGrapth();
		$.DWZajax({
			url : hostUrl + "/defectGraph/selectInspectRecords",
			data : {
				siteCode : data.siteCode,
				attachmentCode : data.attachmentCode,
				processOperationId : data.processOperationId,
				workCenterCode : data.workCenterCode,
				productionControlNum : data.productionControlNum
			},
			callback : function(data) {
				fillDefectGraph(data);
			}
		});
	}, 
	// 初始化视图面板，包括清空缺陷点以及筛选条件
	initGrapth = function(){
		$('#defects_total, #defectGraphHotMap', $graph_panel).empty();
		$('#defectType_filter, #defectLevel_filter, #responsibilityType_filter, #workUnit_filter', $filter_panel).empty().append($('<option/>').val('').append(graphMsg.all));
		$img.hide().removeAttr('src').attr('alt', graphMsg.processAttachmentGraph);
	}, 
	// 填充缺陷视图中的缺陷点以及筛选条件
	fillDefectGraph = function(data) {
		var $defectPoint = $('<a/>').addClass('circle defectPoint'), // 缺陷点模板
		defects = {}, // 缺陷
		defectTypes = {}, // 缺陷类型
		defectLevels = {}, // 缺陷等级 
		responsibilityTypes = {}, // 责任类型
		workUnits = {}; // 工作单元
		
		// 追加缺陷点
		$.each(data, function(index, record){
			// 各种筛选条件去重汇总
			pushFilterObj(defects, record.defectCode, record.defectText);
			pushFilterObj(defectTypes, record.defectTypeCode, record.defectTypeText);
			pushFilterObj(defectLevels, record.defectLevelCode, record.defectLevelText);
			pushFilterObj(responsibilityTypes, record.responsibilityTypeCode, record.responsibilityTypeText);
			pushFilterObj(workUnits, record.workunitCode, record.workunitText);
			
			// 如果数据没有坐标，设置默认坐标
			record.x = record.x || 0;
			record.y = record.y || 0;
			
			var topTem = record.y < 225 ? 0 : 450, leftTem = record.x < 350 ? 0 : 700;
			
			// 追加缺陷点到指定位置，并附加筛选条件，动画显示出来
			var point = $defectPoint.clone(true).data(record).attr({
				defect: record.defectCode || '_blank',
				defectType: record.defectTypeCode || '_blank',
				defectLevel: record.defectLevelCode || '_blank',
				responsibilityType: record.responsibilityTypeCode || '_blank',
				workUnit: record.workunitCode || '_blank'
			}).css({
				background: record.backgroundColor,
				opacity: 0,
				top: topTem,
				left: leftTem,
				display: (window.PIE ? 'none' : 'block')
			}).appendTo($hotMap).animate({
				left: record.x,
				top: record.y,
				opacity: 1
			}, Math.sqrt(Math.pow((record.x - leftTem), 2) + Math.pow((record.y - topTem), 2)) * 0.5, function(){
				if (window.PIE) 
					point.fadeIn(300);
			});
		});
		
		var $defectTypes = $('#defectType_filter', $filter_panel), $defectLevels = $('#defectLevel_filter', $filter_panel), 
			$responsibilityTypes = $('#responsibilityType_filter', $filter_panel), $workUnits = $('#workUnit_filter', $filter_panel);
		
		// 追加筛选条件，根据缺陷筛选
		$.each(defects, function(key, value){
			var $defect = $("a.defectPoint[defect=" + key + "]:eq(0)", $hotMap).clone().removeClass("defectPoint").css({top:'',left:'', opacity: 1, display: 'block'});
			$('<label/>').hide().addClass('defectTypeIcon').append($defect).append(value).appendTo($('#defects_total', $graph_panel)).fadeIn(200);
		});
		
		// 分别填充视图下面的四个筛选下拉框
		fillOptions($defectTypes, defectTypes);
		fillOptions($defectLevels, defectLevels);
		fillOptions($responsibilityTypes, responsibilityTypes);
		fillOptions($workUnits, workUnits);
		
		// IE8 需要渲染圆角
		if (window.PIE) {
			$('.circle', $graph_panel).each(function() {
				PIE.attach(this);
			});
		}
	}, 
	// 筛选条件去重
	pushFilterObj = function(obj, key, value) {
		if (key && !obj[key]) {
			obj[key] = value || key;
		} else if (!key && !obj['_blank']) {
			obj['_blank'] = '';
		}
	}, 
	// 填充select节点
	fillOptions = function($select, options){
		$.each(options, function(value, label){
			$('<option/>').val(value).append(label).appendTo($select);
		});
	}, 
	// 初始化函数，缺陷点事件委托给其所在的div，仅调用一次
	initDefectPointEvent = function() {
		// 缺陷点click事件
		$hotMap.on('click', 'a.defectPoint', function(event){
			var $this = $(this), trData = $.extend({}, $this.data()),
//			url = hostUrl + "/defectGraph/defectDetail_search";
			url = hostUrl + "/inspectRecord/viewInspectRecord";
			// DWZ检测url
			DWZ.debug(url);
			if (!url.isFinishedTm()) {
				alertMsg.error($this.attr("warn") || DWZ.msg("alertSelectMsg"));
				return false;
			}
			// 对Long类型的事件数据进行转换
			if (trData.createDateTime) {
				trData.createDateTime = new Date(parseInt(trData.createDateTime));
			}
			if (trData.modifyDateTime) {
				trData.modifyDateTime = new Date(parseInt(trData.modifyDateTime));
			}
			// 删除不需要使用的两个属性（时间需要转换，否则后台异常）
			delete trData.createDate;
			delete trData.modifyDate;
			// 弹出层显示订单明细以及缺陷详细信息
			$.pdialog.open(url, "DEFECT_DETAIL_INFO", graphMsg.defectInfo, {data: trData, mask: true, width: 900, height: 615, resizable: false});
			event.preventDefault();
			return false;
		});
		// 缺陷点hover事件
		$hotMap.on('mouseenter', 'a.defectPoint', function(){
			var $this = $(this).addClass('hovered');
			if($this.is(":animated")){
				return;
			}
			if ($this.next('.defectInfo').length == 0) {
				new DefectInfo($(this), $(this).data()).showInfo();
			} else {
				$this.next('.defectInfo').fadeIn(100);
			}
		});
		$hotMap.on('mouseleave', 'a.defectPoint', function(){
			var $this = $(this);
			setTimeout(function(){
				if ($this.next('.defectInfo.hovered').length == 1) {
					return;
				}
				$this.next('.defectInfo').hide();
				$this.removeClass('hovered');
			}, 220);
		});
		
	}, 
	// 初始化各种缺陷筛选事件
	initGraphFilterEvent = function() {
		// 总筛选方法，根据节点上是否拥有筛选属性判断该缺陷点是否显示
		var defectPointFilter = function(){
			$.each($('a.defectPoint', $hotMap), function(){
				var $point = $(this),
					filtered = $point.attr('defectFilter') 
					|| $point.attr('defectTypeFilter') 
					|| $point.attr('defectLevelFilter') 
					|| $point.attr('responsibilityTypeFilter') 
					|| $point.attr('workUnitFilter');
				
				if (filtered) {
					$point.fadeOut(200);
				} else {
					$point.fadeIn(200);
				}
			});
		};
		// 缺陷筛选click事件
		$('#defects_total', $graph_panel).on('click', 'label.defectTypeIcon', function(){
			var $this = $(this), defect = $('a:eq(0)', $this).attr('defect');
			if ($this.is('.filtered')) { // 如果已经筛选过，则取消根据缺陷筛选
				$this.removeClass('filtered');
				$('a[defect!=' + defect + ']', $hotMap).removeAttr('defectFilter');
			} else { // 否则追加根据缺陷筛选条件
				$('#defects_total>.filtered').removeClass('filtered');
				$this.addClass('filtered');
				$('a[defect=' + defect + ']', $hotMap).removeAttr('defectFilter');
				$('a[defect!=' + defect + ']', $hotMap).attr('defectFilter', true);
			}
			defectPointFilter();
		});
		// 缺陷视图下面四个下拉框筛选事件
		$('#defectType_filter, #defectLevel_filter, #responsibilityType_filter, #workUnit_filter', $filter_panel).on('change', function(){
			var $this = $(this), filter = this.id.slice(0, -7), filterValue = $('>option:selected', $this).val();
			
			if ($(':first-child:selected', $this).length == 1) { // 如果选择的全部，则取消对应的筛选属性
				$('a[' + filter + ']', $hotMap).removeAttr(filter + 'Filter');
			} else {
				$('a[' + filter + '=' + filterValue + ']', $hotMap).removeAttr(filter + 'Filter');
				$('a[' + filter + '!=' + filterValue + ']', $hotMap).attr(filter + 'Filter', true);
			}
			defectPointFilter();
		});
	};
	
	// 初始化操作
	// 查询订单明细事件绑定
	$("#selectProductionDetails", $tab_panel).on("click", function(){
		var $form = $('#defectGraphSearchFrom', $pg);
		if ($form.valid()) {
			var formData = $form.serializeArray(), data = {};
			$.each(formData, function(index, value){
				data[value.name] = '' || value.value;
			});
			
			try {
				data.startDate = data.startDate.parseDate("yyyy-MM-dd");
				data.endDate = data.endDate.parseDate("yyyy-MM-dd");
				data.endDate.setHours(23, 59, 59, 999);
				if (data.endDate.getTime() < data.startDate.getTime()) {
					alertMsg.error(graphMsg.endDateLessThanStart)
					return false;
				}
			} catch (e) {
				alertMsg.error(e.message);
			}
			selectProductionDetails({
				workCenterCode : data.workCenterCode,
				productionControlNum:data.productionControlNum.trim(),
				productionOrderNum : data.productionOrderNum.trim(),
				materialCode : data.materialCode.trim(),
				materialText : data.materialText.trim(),
				actualstartDateTime : data.startDate,
				actualendDateTime : data.endDate
			});
		}
	});
	$tab_panel.on('keyup', 'input[type="text"],select', function(event){
		var e = event || window.event;
		if (e.keyCode == 13) {
			$("#selectProductionDetails", navTab.getCurrentPanel()).click();
		}
	});
	// 初始化缺陷点点击事件
	initDefectPointEvent();
	// 初始化筛选事件
	initGraphFilterEvent();
	// 初始化图形
	initGrapth();
	// 初始化默认查询时间段
	$('#startDate, #endDate', $tab_panel).val(new Date().formatDate("yyyy-MM-dd"));
	// 点击订单明细，查询相关工艺工序数据
	$('#productionDetailsGrid', $tab_panel).on('click', 'tbody>tr', function(){
		selectProcessOperations($(this).data());
	});
	// 点击工艺工序，查询订单明细相关缺陷数据
	$grid_panel.on('click', 'tbody>tr', function(){
		var $this = $(this), data = $this.data();
		if (!data.workCenterCode || !data.productionOrderNum) {
			data.workCenterCode = $('#productionDetailsGrid tbody tr.selected:first', $tab_panel).data('workCenterCode');
			data.productionOrderNum = $('#productionDetailsGrid tbody tr.selected:first', $tab_panel).data('productionOrderNum');
		}
		selectInspectRecords(data);
		$img.attr({
			'src' : hostUrl + '/common/showAttachement?attachmentCode=' + $this.data('attachmentCode'),
			'alt' : graphMsg.noProcessAttachmentGraph
		}).fadeIn(200);
	});
});

// hover事件展示的缺陷基础信息
DefectInfo = function($ele, eleData) {
	this.panel = $('<div/>').addClass('defectInfo').detach().hide();
	this.brother = $ele;
	this.arrow = $('<div/>').addClass('arrow');
	this.data = {
		defectText: eleData.defectText || '',
		createUser: eleData.createUser,
		createDateTime: new Date(parseInt(eleData.createDateTime)).formatDate("yyyy-MM-dd HH:mm:ss")
	};
	this.top = eleData.y - 7;
	this.left = eleData.x + 16;
}

DefectInfo.prototype = {
	showInfo : function() {
		if (this.left > 500) {
			this.left = this.left - 233;
			this.arrow.addClass('arrow-right');
		} else {
			this.arrow.addClass('arrow-left');
		}
		if (this.top > 375) {
			this.top = this.top - 62;
			this.arrow.css({
				top:'auto',
				bottom: -1
			});
		}
		this.panel.hover(function(){
			$(this).addClass('hovered');
		}, function(){
			var $this = $(this);
			$this.removeClass('hovered').fadeOut(200);
			$this.prev('a.defectPoint').removeClass('hovered');
		}).append(this.arrow).insertAfter(this.brother).data(this.data).css({
			top : this.top,
			left : this.left
		}).append(graphMsg.defectText
				+ this.data.defectText 
				+ '<br>' + graphMsg.inspectRecorder 
				+ this.data.createUser 
				+ '<br>' + graphMsg.inspectDateTime 
				+ this.data.createDateTime).fadeIn(300);
		return this.panel;
	}
};
// checkbox change事件
var hasDefectFilter = function(ele){
	var checked = ele.checked, noDefectSelected = false, $p = navTab.getCurrentPanel();
	$.each($('#productionControlsGrid tbody > tr', $p), function(){
		var $this = $(this);
		if ($(">td.noData", $this).length == 1) {
			return false;
		}
		if ($(">td>.hasDefect", $this).length == 0) {
			if (checked) {
				$this.fadeOut(200);
				if($this.is('.selected')){
					noDefectSelected = true;
				}
			} else {
				$this.fadeIn(200);
			}
		}
	});
	// 如果已经选中没有缺陷的行，再进行过滤，默认去选中第一行，改变已经显示的图片
	if (checked && noDefectSelected) {
		$('#productionControlsGrid tbody > tr > td > .hasDefect:first', $p).click();
	}
};